package br.client;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.rmi.Naming;
import java.rmi.RMISecurityManager;
import java.rmi.RemoteException;

import br.common.Calculadora;
import br.common.remoteobjects.ObjExpressao;

public class CalculadoraCliente {
	
	private Calculadora calcServer;
	
	
	public Calculadora getCalcServer(){
		if (calcServer != null)
			return calcServer;
		try {			
			System.setSecurityManager(new RMISecurityManager());
			this.calcServer = (Calculadora) Naming.lookup("rmi://" + getIPServer() + "/calculadora");			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return calcServer;		
	}
	
	private String getIPServer() {
		try {
			BufferedReader reader =  new BufferedReader(
					new FileReader(System.getProperty("user.dir") + File.separator + "IPServer.txt"));
			return reader.readLine();
		} catch (Exception e) {
			return "localhost";
		}		
	}
	
	public int fazCalculo(int a) throws RemoteException{
		int resp = this.getCalcServer().multiplica(a, 5);
		System.out.println("Resposta do servidor: " + resp);
		return resp;
	}
	
	public ObjExpressao fazSoma(int a,int b) throws RemoteException{
		return this.getCalcServer().somaExpressao(a, b);
	}
}
